import { reqLogin, reqlogout, reqUserInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import {
	SET_USERTOKEN_STATE,
	SET_USERINFO_STATE,
  SET_NAME,
  SET_AVATAR
} from "./constant-type";
const getDefaultState = () => {
  return {
    token: getToken() || "",
    name: "",
    avatar: "",
    userInfo: {}
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  [SET_USERTOKEN_STATE](state, token) {
    state.token = token;
    setToken(token);
  },
  [SET_USERINFO_STATE] (state, payload) {
    state.userInfo = payload.userInfo;
  },
  [SET_NAME](state, name){
    state.name = name;
  },
 [SET_AVATAR] (state, avatar) {
    state.avatar = avatar;
  },
 
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    // console.log(userInfo);
    try {
      const re = await reqLogin(userInfo);
      commit(SET_USERTOKEN_STATE, re.token);
    } catch (e) {
      alert(e.message);
      return Promise.reject();
    }
  },

  // 2.请求用户信息
  async getInfo({ commit },state) {
    try {
      const re = await reqUserInfo();
      commit(SET_USERINFO_STATE, { userInfo: re });
      commit(SET_NAME, re.name);
      commit(SET_AVATAR, re.avatar);
    } catch (e) {
      alert(e.message);
      return Promise.reject(e);
    }
  },
  // user logout
 async logout(state) {
  if(state.name){
    await reqlogout()
  }
  // 删除local中保存的token
  removeToken()
   // 重置路由
   resetRouter()
    // 重置信息
    this.token = ''
    this.name = ''
    this.avatar = ''
 
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
